
import React, { useState, useEffect, useRef ,useContext} from 'react'
import '../../css/public.less'
import './css/OrderListCss/OrderList.less'
import { WechatFilled, AlipayCircleOutlined, SkypeOutlined } from '@ant-design/icons';
import { Input, DatePicker, Space, Button, message, Tag, Table, Modal, DatePickerProps, ConfigProvider, Pagination } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import zh_CN from 'antd/es/locale/zh_CN';
import { useNavigate } from 'react-router-dom'
import createContext from '../../../utils/createContext'
import getSelectTime from '../../../utils/date'
import { getOrderAll, getOrderByCondition } from '../../../api/OrderApi'
// import { number } from 'echarts';

//接口
interface DataType {
	key: React.Key;
	orderId: number;//订单编号
	orderCreated: string;//创建时间
	userId: string; //用户账号
	itemTotal: number;
	paymentMethod: number; //支付方式
	orderSource: number;//订单来源
	orderState: number; //订单状态
	goodsId: number;//商品id
}


const OrderList = () => {
	const navigate = useNavigate()

	const [data, setData] = useState<DataType[]>([])  //所有订单数据
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [loading, setLoading] = useState(false);
	const [Select, SetSelect] = useState('all')  //选择的某个状态的订单数据
	const [pageCount, setPageCount] = useState<number>()  //订单条数
	const [pageSize, setPageSize] = useState<number>(3) //每页条数
	const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
	const [selectState, setSelectState] = useState<number>(10) //当前在哪个状态下
	const [order, setInputOrder] = useState<any>()  //获取订单号输入框的值
	const [user, setInputUser] = useState<string>('')  //获取手机号/用户昵称号输入框的值
	const [dateone, setInputDate] = useState<string>()  //获取时间
	// const context = useContext<any>(createContext)
	const [Count0, setCount0] = useState<number>();
	const [Count1, setCount1] = useState<number>();
	const [Count2, setCount2] = useState<number>();
	const [Count3, setCount3] = useState<number>();
	const [Count4, setCount4] = useState<number>();
	const [Count5, setCount5] = useState<number>();
	const [Count6, setCount6] = useState<number>();
	const [allCount, setAllCount] = useState<number>();


	// const [data, setData] = useState<DataType[]>([
	// 	{
	// 		key: 1,
	// 		id: 1,
	// 		order: `1001`,
	// 		date: `2023-2-27`,
	// 		user: 123,
	// 		money: 100,
	// 		payment: `微信`,
	// 		root: `APP`,
	// 		state: `待付款`,
	// 	},
	// 	{
	// 		key: 2,
	// 		id: 2,
	// 		order: `1002`,
	// 		date: `2023-2-27`,
	// 		user: 123,
	// 		money: 100,
	// 		payment: `微信`,
	// 		root: `APP`,
	// 		state: `待付款`,
	// 	},
	// 	{
	// 		key: 3,
	// 		id: 3,
	// 		order: `1003`,
	// 		date: `2023-2-27`,
	// 		user: 123,
	// 		money: 100,
	// 		payment: `微信`,
	// 		root: `APP`,
	// 		state: `待付款`,
	// 	},
	// 	{
	// 		key: 4,
	// 		id: 4,
	// 		order: `1004`,
	// 		date: `2023-2-27`,
	// 		user: 123,
	// 		money: 100,
	// 		payment: `微信`,
	// 		root: `APP`,
	// 		state: `待付款`,
	// 	},
	// 	{
	// 		key: 5,
	// 		id: 5,
	// 		order: `1005`,
	// 		date: `2023-2-27`,
	// 		user: 123,
	// 		money: 100,
	// 		payment: `微信`,
	// 		root: `APP`,
	// 		state: `待付款`,
	// 	},
	// 	{
	// 		key: 6,
	// 		id: 6,
	// 		order: `1006`,
	// 		date: `2023-2-27`,
	// 		user: 123,
	// 		money: 100,
	// 		payment: `微信`,
	// 		root: `APP`,
	// 		state: `待付款`,
	// 	}
	// ]);

	//日期选择框操作
	const { RangePicker } = DatePicker;
	// console.log('DatePicker',DatePicker);

	// 表格列属性
	const columns: ColumnsType<DataType> = [
		{
			title: '序号',
			dataIndex: 'orderId',
		},
		{
			title: '订单编号',
			dataIndex: 'orderId',
		},
		{
			title: '创建时间',
			dataIndex: 'orderCreated',
		},
		{
			title: '订单金额',
			dataIndex: 'itemTotal',
			render: (_, record) => (
				<Space size="middle">
					<Button type="link">{record.itemTotal}</Button>
					{/* 订单金额为商品单价*商品数量+运费-折扣 */}
				</Space >
			),
		},
		{
			title: '支付方式',
			dataIndex: 'paymentMethod',
			render: (_, record) => (

				record.paymentMethod == 1 ? <Tag icon={<WechatFilled />} color="#55acee">
					微信支付
				</Tag> : record.orderSource == 2 ? <Tag color="#2db7f5" icon={<AlipayCircleOutlined />}>支付宝支付</Tag> :
					<Tag color="#87d068" icon={<SkypeOutlined />}>其他支付</Tag>
				// </Tag>
			),
		},
		{
			title: '订单来源',
			dataIndex: 'orderSource',
			render: (_, record) => (

				record.orderSource == 1 ? <Tag color="#f50">App订单</Tag> : record.orderSource == 2 ? <Tag color="#2db7f5">PC订单</Tag> : <Tag color="#87d068">小程序订单</Tag>
				// </Tag>
			),
		},
		{
			title: '订单状态',
			dataIndex: 'orderState',
			render: (_, record) => (
				record.orderState == 1 ? '待确认' : record.orderState == 2 ? '未支付' : record.orderState == 3 ? '已支付' : record.orderState == 4 ? '未发货' : record.orderState == 5 ? '已发货' : record.orderState == 6 ? '已签收' : '已关闭'
			),
		},
		{
			title: '操作',
			dataIndex: 'operation',
			render: (_, record) => (
				<div className='state-button'>
					<Button onClick={() => { examineBtn(record.orderId, record.orderState, record.goodsId) }} className='one'> 查看订单</Button>
				</div>
			)

		},

	];

	// 初始获取所有订单数据
	useEffect(() => {
		getAllone()
	}, [])


	const getAllone = () => {
		getOrderAll({
			state: selectState,
			pageNum: currentPage,
			size: pageSize
		}).then(res => {
			console.log("res", res);
			setData(res.data.allOrderDtos)
			setPageCount(res.data.count)
			const { OrderCount0, OrderCount1, OrderCount2, OrderCount3, OrderCount4, OrderCount5, OrderCount6, allOrdercount } = res.data.orderCountMap
			setCount0(OrderCount0)
			setCount1(OrderCount1)
			setCount2(OrderCount2)
			setCount3(OrderCount3)
			setCount4(OrderCount4)
			setCount5(OrderCount5)
			setCount6(OrderCount6)
			setAllCount(allOrdercount)
		}).catch(err => {
			console.log('err111', err);
		})

	}


	const start = () => {
		setLoading(true);
		// ajax request after empty completing
		setTimeout(() => {
			setSelectedRowKeys([]);
			setLoading(false);
		}, 1000);
	};

	// const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
	// 	console.log('selectedRowKeys changed: ', newSelectedRowKeys);
	// 	setSelectedRowKeys(newSelectedRowKeys);
	// };

	// const rowSelection = {
	// 	selectedRowKeys,
	// 	onChange: onSelectChange,
	// };
	// const hasSelected = selectedRowKeys.length > 0;


	//点击查看详情跳转页面

	//点击查看订单详情
	const examineBtn = (orderId: number, status: number, goodsId: number) => {
		console.log('打印v', goodsId);
		navigate('/home/order/OrderDetails', { state: { orderId, status, goodsId } })
	}

	// 点击头部按钮选择显示所有订单、代付款、待发货、已发货、已完成、已关闭
	const onClickBtn = (type: string, state: number) => {
		console.log('点击了哟，颜色改变');
		SetSelect(type)
		setSelectState(state)
		getOrderAll({
			state: state,
			pageNum: currentPage,
			size: pageSize,
		}).then(res => {
			setData(res.data.allOrderDtos)
			SetSelect(type)
			console.log('点击导航按钮查询', res.data.count);
			setPageCount(res.data.count)
		}).catch(err => {
			console.log('err222', err);

		})
	}

	//页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
	const pageChange = (page: number, pageSize: number) => {
		console.log('page pageSize state', page, pageSize);
		setPageSize(pageSize)
		setCurrentPage(page)
		getOrderAll({
			state: selectState,
			pageNum: page,
			size: pageSize,
		}).then(res => {
			setData(res.data.allOrderDtos)
			setPageCount(res.data.count)
			// 设置当前页和每页条数
			setPageSize(pageSize)
			setCurrentPage(page)
		}).catch(err => {
			console.log('err222', err);

		})
	}

	//筛选
	////获取订单号输入框的值
	const handleChange = (e: any) => {
		let order = e.target.value
		setInputOrder(order);
		console.log('order', order);
	}
	//获取手机号/用户昵称号输入框的值
	const handleChange1 = (e: any) => {
		let user = e.target.value
		setInputUser(user);
		console.log('usre', user);

	}
	//获取时间
	const handleChange2: DatePickerProps['onChange'] = (date, dateString) => {

		console.log('谁记得手机号',dateString);
		
		// getSelectTime(dateString)
		// console.log('时间来了',dateString);
		
		setInputDate(dateString);
		console.log('获取到了时间',dateone);
		
		console.log('date', dateString);

	}
	//点击筛选按钮
	const filterInput = () => {
		getOrderByCondition({
			// orderCreated: date, //创建时间 
			orderId: Number(order),
			// orderState: selectState,
			page: currentPage,//当前页
			size: pageSize,//每页多少条
			userPhone: user,//收货人手机号
		}).then(res => {
			console.log('根据条件查询订单结果res', res.data);
			// if(res.code==200){
			console.log(111111111);
			// setPageCount(res.data.count)
			setData(res.data.allOrderDtos);
			if (res.data.allOrderDtos.length > 0) {
				// 查询出有数据
				message.success('查询订单成功')
			} else {
				// 没有数据
				// message.info(res.msg)
				message.info('没有数据')

			}
			// }

		}).catch(err => {
			console.log('err333', err);
			message.error('服务器错误')
		})


	}

	//重置按钮
	const rest = (event: any) => {
		// 阻止默认事件
		event.preventDefault()
		console.log('重置');
		// 清空搜索框
		setInputOrder('');
		setInputUser('');
		setInputDate('');

		// 重置 重新获取数据
		getOrderAll({
			state: 10,
			pageNum: currentPage,
			size: pageSize,
		}).then(res => {
			setData(res.data.allOrderDtos)
			console.log('点击重置', res.data.count);
			setPageCount(res.data.count)
		}).catch(err => {
			console.log('err222', err);
		})
	}

	return (
		<div className='OrderList'>
			{/* <createContext.Provider value={{ getAllone }}> */}
			{/* 头部 */}
			<div className='page-top'>
				{/* 左边标题 */}
				<div className='page-title'>
					<p>订单列表</p>
				</div>
			</div>
			<div className='page-div-top'>
				<div className={Select == 'all' ? 'selectBtn' : ''} onClick={() => onClickBtn('all', 10)}>全部订单( <p>{allCount}</p> )</div>
				<div className={Select == 'waitConfirm' ? 'selectBtn' : ''} onClick={() => onClickBtn('waitConfirm', 1)}>待确认( <p>{Count1}</p> )</div>
				<div className={Select == 'waitPay' ? 'selectBtn' : ''} onClick={() => onClickBtn('waitPay', 2)}>未支付( <p>{Count2}</p> )</div>
				<div className={Select == 'payFinish' ? 'selectBtn' : ''} onClick={() => onClickBtn('payFinish', 3)}>已支付( <p>{Count3}</p> )</div>
				<div className={Select == 'waitDeliver' ? 'selectBtn' : ''} onClick={() => onClickBtn('waitDeliver', 4)}>未发货( <p>{Count4}</p> )</div>
				<div className={Select == 'deliverFinish' ? 'selectBtn' : ''} onClick={() => onClickBtn('deliverFinish', 5)}>已发货( <p>{Count6}</p> )</div>
				<div className={Select == 'signFinish' ? 'selectBtn' : ''} onClick={() => onClickBtn('signFinish', 6)}>已签收( <p>{Count5}</p> )</div>
				<div className={Select == 'close' ? 'selectBtn' : ''} onClick={() => onClickBtn('close', 0)}>已关闭( <p>{Count0}</p> )</div>
			</div>
			{/* 内容区 */}
			<div className='page-context' style={{ paddingTop: '10px' }}>

				{/* 查询部分 */}
				<div className='banner-search'>
					<div className='banner-query'>
						<p>筛选查询</p>
					</div>
					<div className='banner-input'>
						<div className='banner-input-div'>关键词<Input value={order} onChange={handleChange} placeholder="订单号/商品货号" /></div>
						<div>收货人<Input placeholder="手机号/用户昵称" value={user} onChange={handleChange1} /></div>
						<div className='banner-input-date'>提交时间<DatePicker onChange={handleChange2} renderExtraFooter={() => 'extra footer'} showTime placeholder="请选择时间" style={{ width: '250px', height: '35px', marginLeft: '18px' }} /></div>
					</div>
					<div className='banner-button'>
						<Button type="primary" className='reset' onClick={rest}>重置</Button>
						<Button type="primary" className='filter' onClick={filterInput}>筛选</Button>
					</div>

				</div>
				{/* 数据表格部分 */}
				<div className='data-list'>
					<div className='data-list-div'>
						<p>数据列表</p>
						<div className='data-list-context'>
							<div style={{ marginBottom: 2 }}>
								<span style={{ marginLeft: 8 }}>
									{/* {hasSelected ? ` ${selectedRowKeys.length} ` : ''} */}
								</span>
							</div>
							<ConfigProvider locale={zh_CN}>
								<Table
									// rowSelection={rowSelection}
									rowKey={(item) => item.orderCreated}
									columns={columns}
									dataSource={data}
									pagination={
										{
											position: ['bottomCenter'],
											total: pageCount,
											defaultPageSize: pageSize,
											defaultCurrent: currentPage,
											pageSizeOptions: [4, 8, 12],
											showQuickJumper: true,
											showSizeChanger: true,
											onChange: pageChange,
											showTotal: (total: number) => `共有 ${total} 条数据`
										}
									}
								/>
							</ConfigProvider>
						</div>
					</div>
				</div>
			</div>
			{/* </createContext.Provider> */}
		</div>
	)
}


export default OrderList